﻿using Infra_common.YIBanUrl;
using MediatR;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using xiaodingmarket_Domain.Commands.Sell;
using xiaodingmarket_Domain.Events.Commodity;
using xiaodingmarket_Domain.Events.Sell;
using xiaodingmarket_Domain.Interfaces;
using xiaodingmarket_Domain.Interfaces.IRepository;
using xiaodingmarket_Domain_core.Bus;
using xiaodingmarket_Domain_core.Notificatiions;

namespace xiaodingmarket_Domain.CommandHandlers
{
    public class SellCommandHandler : CommandHandler,
        IRequestHandler<WantAndTobeFriendCommand, bool>
    {
        private readonly IMediatorHandler Bus;
        private readonly ICommodityRepository _CommodityRepository;
        private readonly IUserRepository _userRepository;
        private readonly YBUrl _yburl;
       public SellCommandHandler(ICommodityRepository CommodityRepository,
                                      IUserRepository UserRepository,
                                      IUnitOfWork uow,
                                      IMediatorHandler bus,
                                      YBUrl yburl,
                                      INotificationHandler<DomainNotification> notifications) : base(uow, bus, notifications)
        {
            Bus = bus;
            _CommodityRepository = CommodityRepository;
            _userRepository = UserRepository;
            _yburl = yburl;
        }

        public Task<bool> Handle(WantAndTobeFriendCommand request, CancellationToken cancellationToken)
        {
            var commodity = _CommodityRepository.GetById(request.commodityid);
            var user = _userRepository.GetById(request.Sellerid);//用来取出用户的易班id
            //首先确认是不是已经为好友（以下这些api的访问代码以后再封装成一个类方法）
            
            string responseContent = _yburl.Getapi("https://openapi.yiban.cn/friend/check?access_token=" + request.access_token + "&yb_friend_uid=" + user.Userid);

            //解析json
            var response = new { statu = "", info = "" };
            var Result = JsonConvert.DeserializeAnonymousType(responseContent, response);
            if (Result.statu.Equals("success"))
            {
                if (Result.info.Equals("true")) //是好友
                {
                    //直接发event，通知卖家谁想买你东西
                    Bus.RaiseEvent(new WantAndTobeFriendEvent(commodity.CommodityDetail.StudentId,request.commodityid,request.wanterid));
                }
                else
                {
                    //发送加好友申请，并发event
                   
                    string responseContent1 = _yburl.Getapi("https://openapi.yiban.cn/friend/apply?access_token=" + request.access_token + "&yb_friend_uid=" + user.UserName + "&content=" + "你好，我看中了您发布的    " + commodity.CommodityDetail);

                    var Result1 = JsonConvert.DeserializeAnonymousType(responseContent1, response);
                    if (Result1.statu.Equals("success"))
                    {
                        Bus.RaiseEvent(new WantAndTobeFriendEvent(commodity.CommodityDetail.StudentId, request.commodityid, request.wanterid));
                    }
                    //修改商品表
                    commodity.Wanterid+=request.wanterid;
                    commodity.wanter++;
                    _CommodityRepository.Update(commodity);
                    if (Commit())
                    {
                        Bus.RaiseEvent(new CommodityUpdateEvent(request.Sellerid,request.commodityid));
                    }
                }
            }
            else
            {
                throw new Exception("访问易班好友接口错误");
            }



            return Task.FromResult(true);
        }
    }
}
